<template>
  <view>
    <!--    @wapperClick="clickGood"  这里取消视频下面的点击事件-->
    <kristen-trends-list :trendsList="list" :mpGoodsShow="'imgUpTxtDown'" @clickTrends="clickGood"></kristen-trends-list>

    <u-modal v-model="visible" ref="uModal" show-cancel-button confirm-text="确认下载" @confirm="toShowMyDownloadTime()"
    >
      <view style="margin: 16px">
        <view>
                  <span>为保障每位伙伴下载素材的原创性，每条素材只能下载1次。多次下载需点击<span
                      @click.stop="applyDownload"
                      style="text-decoration: underline;color: green;">申请下载</span></span>
        </view>
        <view style="margin-top: 15px;color: red;">
          <span>注意：视频文案可通过个人中心的下载历史中进行查看</span>
        </view>
      </view>
    </u-modal>


    <u-modal v-model="showMyDownloadTime" confirm-text="关闭" title="使用次数" ref="uModalApplyTime">
      <u-tabs :list="tabsList"
              :current="tabsCurrent"
              :is-scroll="false"
              @click="tabsClick"
              @change="tabsChange"
              :show-bar="false"></u-tabs>


      <view v-if="tabsCurrent === 0">
        <view v-if="listType1.length>0">
          <uni-list :border="true" v-for="(item,index) in listType1" :key="index">
            <uni-list-item link @click="verifyTrendsDownload(item.walkTrendsDownloadNum.id)">
              <template v-slot:header>
                <span v-if="item.pmsGoods">{{ item.pmsGoods.title }}</span>
                <span v-else>所有商品</span>
              </template>
              <template v-slot:footer style="margin-left: 20px">
                <span v-if="item.walkTrendsDownloadNum.source===2">申请次数:{{ item.walkTrendsDownloadNum.num }}</span>
                <span v-if="item.walkTrendsDownloadNum.source===1">赠送次数:{{ item.walkTrendsDownloadNum.num }}</span>,
                <span
                    v-if="item.walkTrendsDownloadNum.status===1">可用次数:{{ item.walkTrendsDownloadNum.useNum }}</span>

              </template>
            </uni-list-item>

          </uni-list>
        </view>
        <no-data :list="listType1"></no-data>
      </view>

      <view v-if="tabsCurrent === 1">
        <view v-if="listType3.length>0">
          <uni-list :border="true" v-for="(item,index) in listType3" :key="index">
            <uni-list-item link @click="verifyTrendsDownload(item.walkTrendsDownloadNum.id)">
              <template v-slot:header>
                <span v-if="item.pmsGoods">{{ item.pmsGoods.title }}</span>
                <span v-else>所有商品</span>
              </template>
              <template v-slot:footer style="margin-left: 20px">
                <span v-if="item.walkTrendsDownloadNum.source===2">申请次数:{{ item.walkTrendsDownloadNum.num }}</span>
                <span v-if="item.walkTrendsDownloadNum.source===1">赠送次数:{{ item.walkTrendsDownloadNum.num }}</span>,
                <span
                    v-if="item.walkTrendsDownloadNum.status===1">可用次数:{{ item.walkTrendsDownloadNum.useNum }}</span>
              </template>
            </uni-list-item>

          </uni-list>
        </view>
        <no-data :list="listType3"></no-data>
      </view>
    </u-modal>

    <toDownloadApplyModal ref="toDownloadApplyModal"></toDownloadApplyModal>
  </view>

</template>
<style scoped>
.van-icon-play::before {
  /* #ifdef MP-WEIXIN */
  position: relative;
  top: -1px;
  left: 1px;
  /* #endif */
}

.find-menu-btn {
  position: absolute;
  right: 4px;
  top: 4px;
  padding: 6px;
  border-radius: 50%;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1;
}

.wrap-layout {
  position: absolute;
}

.wrap-layout view {
  background-color: rgba(0, 0, 0, 0.3);
}

.find-status {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 11;
}

.play-role {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: rgba(0, 0, 0, 0.3);
}

.line-h16 {
  position: relative;
  top: 1px;
}

.walkMemberNameFont {
  width: 60px; /* 指定容器的宽度 */
  white-space: nowrap; /* 防止换行 */

  text-overflow: ellipsis; /* 使用省略号表示被裁切的文本 */
  display: inline-block !important;
}
</style>

<script>


const API = require('@/utils/api/find.js').default;
const $ = require('../../../utils/api.js');
import toDownloadApplyModal from '../../common/toDownloadApply.vue';
import KristenTrendsList from "@/uni_modules/trends-list/kristen-trendsList.vue";

export default {
  components: {toDownloadApplyModal,KristenTrendsList},
  name: "findlistChild",
  props: {
    location: {
      type: Number,
      default: 1
    },
    isAi: {
      type: Boolean,
      default: false
    },
    logo:{
      type: String,
      default: ""
    },
    isOnlyOne: {
      type: Boolean,
      default: false
    },
    isGg: {
      type: Boolean,
      default: false
    },
    modeType: {
      type: String,
      default: "scaleToFill"
    },
    goodsId: {
      default: '',
    },
    list: {
      type: Array,
      required: true
    },
    // offset 间距，单位为 px
    offset: {
      type: Number,
      default: 1.2
    },
    // 列表渲染的 key 的键名，值必须唯一，默认为 id
    idKey: {
      type: String,
      default: "id"
    },
    // 图片 src 的键名
    imageSrcKey: {
      type: String,
      default: "mainImg"
    },
    // 列数
    cols: {
      type: Number,
      default: 2,
      validator: (num) => num >= 1
    },
    imageStyle: {
      type: Object
    },

    // 是否是单独的渲染图片的样子，只控制图片圆角而已
    single: {
      type: Boolean,
      default: false
    },

    // #ifndef MP-WEIXIN
    listStyle: {
      type: Object
    },
    // #endif
    isSelf: {
      type: Boolean,
      default: false
    },
    userId: {
      default: ''
    },
    pages: {
      default: ''
    }
  },

  data() {
    return {
      isShowWatermark: uni.getStorageSync('config').is_open_watermark_img == '1' ? true : false,
      watermarkContent: uni.getStorageSync('config').watermark_content_img,
      tempCount: 0,
      showMyDownloadTime: false,
      startDate: new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate(),
      chooseUseTime: '请选择使用日期',
      currentVerifyNumItem: {},
      visibleVerifyNum: false,
      currentItem: {},
      currentIndex: 0,
      showDownload: true,
      downloadingButtonLabel: "",
      visible: false,
      showMenu: false,
      showIndex: '',
      tabsCurrent: 0,
      page: 1,
      pageSize: 20,
      listType1: [],
      listType3: [],
      tabsList: [],
      tabsListVideo: [{
        name: "短视频素材",
      }],
      tabsListImg: [{
        name: '图片素材',
      }],
    };
  },
  onLoad: function () {
    this.init();
  },
  methods: {
    showThisContent(data) {
      $.$toast(data)
    },
    showAllShopName(shopName) {
      $.$toast(shopName);
    },
    refreshNext() {
      this.$refs.waterfallsFlowRef.refresh()
    },
    tabsClick(item) {
      console.log('item', item);
    },
    tabsChange(index) {
      this.tabsCurrent = index;
    },
    getChooseTime(data) {
      this.chooseUseTime = data.detail.value
    },
    applyDownload() {
      this.$refs.toDownloadApplyModal.init();
    },

    gotoDownload(item) {
      this.visible = true
      this.currentIndex = item.index
      this.currentItem = item
    },
    gotoDownloadH5(item) {
      uni.showToast({
        title: "当前是H5页面。请移步到小程序进行下载",
        icon: "none"
      });
    },


    toShowMyDownloadTime() {
      let type = this.currentItem.type
      if (type === 1) {
        this.tabsList = this.tabsListVideo
      } else if (type === 3) {
        this.tabsList = this.tabsListImg
      }
      this.showMyDownloadTime = true
      this.getListMyDownloadTime(1)
      this.getListMyDownloadTime(3)
    },

    getListMyDownloadTime(type) {

      const self = this;
      $.ajax({
        url: API.getVerifyTrendsDownloadNumListToUse,
        data: {
          goodsId: self.goodsId,
          type: type,
          page: self.page,
          pageSize: self.pageSize
        },
        loading: true,
        method: 'GET',
        success(res) {
          if (type === 1) {
            self.listType1 = res.data.list
          } else if (type === 3) {
            self.listType3 = res.data.list
          }


        }
      })
    },


    verifyTrendsDownload(id) {
      const self = this
      $.ajax({
        url: API.verifyTrendsDownload,
        data: {
          "id": id,
          "goodsId": self.goodsId,
          "trendsId": self.currentItem.id
        },
        method: 'GET',
        success(res) {
          self.toDownload(id)
        }
      })
    },
    toDownload(downloadNumId) {
      this.showMyDownloadTime = false
      // 跳转到新webview页面，encodeURIComponent：url参数中出现空格等特殊字符时需要对参数进行编码
      // uni.navigateTo({
      //   url: '/pages/webview/webview?url=' + encodeURIComponent(this.url)
      // })
      let index = this.currentIndex
      let type = this.currentItem.type

      this.visible = false
      // 下面的方式只支持除了H5以外的平台
      const self = this;
      let info = self.list[index];
      let url
      if (type === 1) {
        url = info.videoUrl
      } else if (type === 3) {
        url = info.mainImg
      }
      const downloadTask = uni.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({
              title: "视频连接正确",
              icon: "none"
            });
            if (type === 1) {
              uni.saveVideoToPhotosAlbum({
                filePath: res.tempFilePath,
                success: function () {
                  info.showDownload = true
                  self.list[index] = info;
                  uni.showToast({
                    title: "保存成功",
                    icon: "none"
                  });

                  self.addTrendsDownloadLog(self.list[index], downloadNumId)

                },
                fail: function (e) {
                  info.showDownload = true
                  self.list[index] = info;
                  console.log(e)
                  uni.showToast({
                    title: "保存失败，请稍后重试",
                    icon: "none"
                  });
                }
              });
            } else if (type === 3) {
              uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: function () {
                  info.showDownload = true
                  self.list[index] = info;
                  uni.showToast({
                    title: "保存成功",
                    icon: "none"
                  });
                  self.addTrendsDownloadLog(self.list[index], downloadNumId)

                },
                fail: function (e) {
                  info.showDownload = true
                  self.list[index] = info;
                  console.log(e)
                  uni.showToast({
                    title: "保存失败，请稍后重试",
                    icon: "none"
                  });
                }
              });
            }

          }
        }
      });

      downloadTask.onProgressUpdate((res) => {
        info.showDownload = false
        if (res.progress < 100) {
          info.downloadingButtonLabel = "下载中：" + res.progress + "%"
        } else {
          info.downloadingButtonLabel = "下载完成"
        }
        self.list[index] = info;
        console.log(self.list[index])
        console.log('下载进度' + res.progress);
        console.log('已经下载的数据长度' + res.totalBytesWritten);
        console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
      });
    },

    addTrendsDownloadLog(data, downloadNumId) {
      $.ajax({
        url: API.addTrendsDownloadLog,
        data: {
          "publishWalkMemberId": data.walkMemberId,
          "publishWalkMemberName": data.walkMemberName,
          "publishWalkMemberHeadImg": data.walkMemberHeadImg,
          "trendsId": data.id,
          "videoUrl": data.type === 1 ? data.videoUrl : "",
          "imgUrl": data.mainImg,
          "type": data.type,
          "content": data.content,
          "downloadNumId": downloadNumId,
        },
        method: 'POST',
        success(res) {
          $.$toast('已生成下载记录');
        }
      })
    },


    edit(info) {
      uni.setStorageSync('findDetail', info);
      // this.go('/pagesA/find/issue?type=' + info.type + '&id=' + info.id);
    },
    like(index) {

      const self = this;
      let info = self.list[index];
      $.ajax({
        url: API.likeFindApi,
        data: {
          trendsId: info.id
        },
        method: 'POST',
        loading: true,
        success(res) {
          $.$toast(self.i18n['操作成功']);
          info.collectTrends = !info.collectTrends;
          if (info.collectTrends) {
            info.collectionNum += 1;
          } else {
            info.collectionNum -= 1;
          }
          self.list[index] = info;
          self.tempCount++;
          uni.hideLoading(); // 加载成功后隐藏加载提示
        }
      })
    },
    del(index) {
      const self = this;
      let info = this.list[index];
      $.showModal({
        content: '是否确认删除',
        success() {
          let url = 'member/trends/delete';
          let postData = {ids: info.id}
          if (self.pages == 'user') {
            url = 'member/trends/deleteMyCollection';
            postData = {id: info.id}
          }
          $.ajax({
            url: url,
            data: postData,
            method: 'POST',
            success(res) {
              self.$emit('del', index)
            }
          })
        }
      }, this)
    },
    show(index) {
      this.showIndex = index;
      this.showMenu = !this.showMenu;
    },
    verifyTrendsDownloadByOther(data) {
      const self = this
      $.ajax({
        url: API.verifyTrendsDownloadIsOther,
        data: {
          "trendsId": data.id
        },
        loading: true,
        method: 'GET',
        success(res) {
          let isSelf = self.isSelf ? 1 : 0;
          if (data.type == 1) {
            let isGg = self.isGg ? self.isGg : false
            let isOnlyOne = self.isOnlyOne
            let onlyOneTrendsId = "";
            if (self.isAi){
              isOnlyOne = true
            }
            if (isOnlyOne) {
              onlyOneTrendsId = data.id;
            }

            $.go('/pagesA/find/video?id=' + data.id +'&location=' + self.location + '&isSelf=' + isSelf + '&userId=' + self.userId + '&isGg=' + isGg + '&onlyOneTrendsId=' + onlyOneTrendsId);
          } else if (data.type == 3) {
            let url = data.images
            if (self.isShowWatermark) {
              url = url + "-" + self.watermarkContent
            }
            uni.previewImage({
              urls: [url], // 需要预览的图片链接列表
            });
          } else {
            if (self.pages == 'user') {
              $.go('/pagesB/user/finddetail?id=' + data.id);
            } else {
              $.go('/pagesA/find/detail?id=' + data.id + '&isSelf=' + isSelf + '&userId=' + self.userId);
            }
          }
        },

      })
    },
    clickGood(data) {
      this.verifyTrendsDownloadByOther(data)
    },
    init() {

    },


  },
  computed: {
    i18n() {
      return this.$t('find')
    },
  },

  created() {
  },
  mounted() {
  },
  destroyed() {
  },
  onPullDownRefresh() {

  },
  onReachBottom() {
  }
}
</script>
